﻿using System;
using System.Data.Entity;
using System.Data.Common;
using Rainr.EFClient.Transaction;

namespace Rainr.EFClient
{
    /// <summary>
    /// 数据访问基类
    /// </summary>
    /// <typeparam name="TContext">数据上下文类型</typeparam>
    public abstract class DbAccessorBase<TContext> : IEntityTransaction
        where TContext : DbContext, new()
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public DbAccessorBase()
        {
            this.Context = new TContext();
        }

        /// <summary>
        /// 启动事务。
        /// </summary>
        public virtual void BeginTransaction()
        {
            this.IsTransaction = true;
        }
        /// <summary>
        /// 提交事务，如果提交失败则会自动回滚。
        /// </summary>
        public virtual void SubmitTransaction()
        {
            this.IsTransaction = false;
            this.SaveChanges();
        }
        /// <summary>
        /// 提交改变至持久数据库。如果当前处于事务中，则会在提交事务时进行提交。
        /// </summary>
        protected virtual void SaveChanges()
        {
            if (!this.IsTransaction)
            {
                this.Context.SaveChanges();
            }
        }
        /// <summary>
        /// 数据上下文对象。
        /// </summary>
        public virtual TContext Context { get; private set; }
        /// <summary>
        /// 当前是否处于事务中。
        /// </summary>
        protected bool IsTransaction { get; private set; }
    }
}
